/*
package thread;

import java.util.PriorityQueue;

*/
/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2024-09-26
 * Time: 15:54
 *//*


class MyTimer {//计时器中的线程负责扫描队列任务
    private Thread t = null;
    public Object locker = new Object();

    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    public void schedule(Runnable runnable , long delay){
       synchronized(locker){
           MyTimerTask task = new MyTimerTask(runnable , delay);
           queue.offer(task);
           locker.notify();
       }
    }
    public MyTimer(){//t线程去扫描队列，判断是否要执行任务
        t = new Thread(()->{
            while (true){
                try{
                    synchronized(locker){
                        while(queue.isEmpty()){
                            locker.wait();
                        }

                        //不为null拿到队首元素
                        MyTimerTask task = queue.peek();
                        if (System.currentTimeMillis() >= task.getTime()  ){
                            queue.poll();
                            task.run();
                        }else {
                            locker.wait(task.getTime()-System.currentTimeMillis());
                        }
                    }

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }


        });
        t.start();
    }


}

class MyTimerTask implements Comparable<MyTimerTask>{//描述一个任务，并把这个任务扔到队列里面去
    private long time;//绝对时间
    private Runnable runnable;
    public long getTime(){
        return time;
    }
    public  MyTimerTask(Runnable runnable , long delay){
        this.time = System.currentTimeMillis() + delay;
        this.runnable = runnable;
    }
    public void run(){
        runnable.run();
    }
    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time - o.time);
    }
}
public class ThreadDemon33_2 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("任务一1s");
            }
        },1000);

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("任务二2秒");
            }
        },2000);
        System.out.println("main函数");



    }

}
*/
